package com.co.vote.web.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.co.server.entity.user.TUsers;
import com.co.server.entity.user.aide.TUsersConstant;
import com.co.server.service.user.TUsersService;
import com.co.server.service.user.impl.UsersSession;
import com.co.vote.constant.SessionConstant;
import com.co.vote.web.base.BaseControllerImpl;


public class sessionInterceptor  extends HandlerInterceptorAdapter {

	@Resource
	TUsersService tUsersService;
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object arg) throws Exception {
		UsersSession usersSession = (UsersSession)request.getSession().getAttribute(SessionConstant.SESSION_USER);
		TUsers guest= null;
		if(usersSession==null){
			usersSession = new UsersSession();
			guest = tUsersService.queryById(TUsersConstant.USER_GUEST_ID);
			usersSession.settUsers(guest);
			request.getSession().setAttribute(SessionConstant.SESSION_USER, usersSession);
		}
		
		if(arg instanceof HandlerMethod){
			HandlerMethod  hm=(HandlerMethod) arg;
			RequestMapping annotation = hm.getBeanType().getAnnotation(RequestMapping.class);
			if(annotation !=null){
				String value = annotation.value()[0];
				Object bean = hm.getBean();
				if(bean instanceof BaseControllerImpl){
					BaseControllerImpl<?>  bci= ((BaseControllerImpl<?>) bean);
					bci.setReturnPath(value);
					bci.setUsersSession(usersSession);
				}
			}
		}
		return true;
	}
	
}
